package com.share.three.netty.fixedLength;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class ServerHandler extends ChannelHandlerAdapter{
	
	private static final Object String = null;

	/* 
	 * 在连接被创建时，执行此方法
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("server channel active");
	}

	/*
	 * 当收到client端发送过来的数据时，执行此方法
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		try {
			String receive = (String)msg;
			System.out.println("server 接收： " + receive);
			final String send = receive;
			ChannelFuture f = ctx.writeAndFlush(Unpooled.copiedBuffer((send).getBytes()));
			f.addListener(new ChannelFutureListener() {
				
				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					System.out.println("server 发送： " + send);
					
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * 当发生异常时，执行此方法
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	

}
